package org.ecype.diego;

import java.lang.reflect.Field;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import androidx.persistence.access.Incrementer;

public class IncrementerProcessor extends ActionUriProcessor {

	private String column;
	private String[] columnAsArray;

	@Override
	public void setup(ContractContentProvider provider, Field field) {
		super.setup(provider, field);
		Incrementer annotation = field.getAnnotation(Incrementer.class);
		column = annotation.column();
		columnAsArray = new String[] { column };
	}

	@Override
	public int update(Uri action, Uri notifyUri, ContentValues params, String selection, String[] selectionArgs) {
		Uri uri = Uris.withoutLastSegment(action);
		Cursor object = provider.query(uri, columnAsArray, null, null, null);
		object.moveToFirst();
		long value = Cursors.getLong(object, column);
		value += params.getAsLong(Incrementer.INCREMENT);
		object.close();
		ContentValues values = new ContentValues();
		values.put(column, value);
		return provider.update(uri, notifyUri, values, null, null);
	}
}
